import { State } from "../core/state";
import { createLogger } from "../core/utils/logging";
import { GameCore } from "../game/core";
import { getRandomHint } from "../game/hints";

const logger = createLogger('state/game')

export class GameState extends State{
  constructor(){
    super('GameState')
  }

  getInnerHTML(){
    return `
      <header>
        <div class="left">
          欢迎来到天元大陆
        </div>
        <div class="right">
          <button class="tipButton"><img src="res/ui/icons/tip.svg" /></button>
          <button class="settingButton"><img src="res/ui/icons/setting.svg" /></button>
        </div>
      </header>
    `
  }

  onEnter(){
    this.loadingDialog = null;

    this.showLoading();
    this.handlerButtonCallback();
    this.stage1GetGameData();
  }

  showLoading(){
    this.hideLoading();
    this.loadingDialog = this.dialogs.showGameLoadingDialog(getRandomHint());
  }

  hideLoading(){
    this.loadingDialog && this.loadingDialog();
    this.loadingDialog = null;
  }

  handlerButtonCallback(){
    let settingButton = this.htmlElement.querySelector('.settingButton');

    this.trackClicks(settingButton, () => {
      this.moveToStateAddGoBack('SettingState')
    })

    this.trackClicks(this.htmlElement.querySelector('header .left'), () => {
      if(this.core){
        this.core.root.hud.parts.logBoard.internalShow();
      }
    })
  }

  stage1GetGameData(){
    logger.log('检测游戏数据')

    let playerData = this.app.savegame.getPlayerData();

    if(!playerData.troops.length){
      logger.warn('没有读取到玩家数据');
      this.dialogs.showWarning('游戏数据错误', '没有读取到玩家数据，请重新创建新游戏。', ['ok:good:确认']).ok.add(() => {
        this.app.savegame.deleteAllData().then(() => {
          this.moveToState('MainMenuState');
        })
      })
      return;
    }

    this.stage2CreateGameCore();
  }

  stage2CreateGameCore(){
    logger.log('创建游戏核心');

    this.core = new GameCore(this.app);
    this.core.initializeRoot(this)

    this.stage10Success();
  }

  onResized(width, height){
    if(this.core){
      this.core.onResized(width, height);
    }
  }

  stage10Success(){
    logger.log('✅ 初始化完毕，游戏开始');

    this.core.root.gameInitialized = true;
  }

	onRender(dt) {
    // this.showLoadingHint();

    if(this.core){
      this.core.update(dt);
    }
  }

  showLoadingHint(){
    const now = performance.now();
    if(now - this.lastHintShown > this.nextHintDuration){
			this.lastHintShown = now;
      const hintText = getRandomHint();

			this.loadingElement.innerHTML = hintText;

			/**
       * 以每分钟500个字符的阅读速度计算
			 */
			this.nextHintDuration = Math.max(2500, (hintText.length / 500) * 60 * 1000);
		}
  }

  onAppPause(){
    if(this.core){
      this.core.root.stopGame();
    }
  }

  onAppResume(){
    if(this.core){
      this.core.root.playGame();
    }
  }

  stageDestroyed(){
    if(this.core){
      this.core.destruct();
      this.core = null;
    }
  }

  onLeave(){
    this.stageDestroyed();
  }
}